<template>
  <div class="editMaterial">
    <div style="margin-bottom: 10px">
      <jc-button
        :btn-arr="['reload', 'save', 'sub', 'pass', 'list', 'remove']"
        :list="'/technologyList'"
        @refresh="queryWorkshopDetail"
        @save="preserve"
        @audit="audit(1)"
        @noAudit="audit(2)"
        @submit="preserve(1)"
        @noSubmit="proSubmit(2)"
        @del="delTechno"
      />
    </div>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane :label="$t('market.info')" name="first">
        <el-form ref="process" :model="process" label-width="100px" :rules="processRules" size="mini">
          <el-form-item :label="$t('market.documentstatus')">
            <el-tag :type="process.stateColor">{{ process.fdocumentstatus }}</el-tag>
          </el-form-item>
          <el-form-item :label="$t('market.deaprt')" prop="fdeptId">
            <el-input v-model.trim="process.fdeptName" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.craftnumber')">
            <el-input
              v-model.trim="process.fnumber"
              disabled
            />
          </el-form-item>
          <el-form-item :label="$t('market.fcraftname')" prop="fname">
            <el-input
              v-model.trim="process.fname"
              :disabled="isDisabled"
            />
          </el-form-item>
          <el-form-item :label="$t('market.fmodel')" prop="fmodel">
            <el-input
              v-model.trim="process.fmodel"
              :disabled="isDisabled"
            />
          </el-form-item>
          <el-form-item :label="$t('market.totalAmount')" prop="totalAmount">
            <el-input v-model.trim="process.fsumprice" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.orderTime')" prop="fcreateTime">
            <el-date-picker
              v-model="process.fcreateTime"
              type="date"
              :disabled="isDisabled"
            />
          </el-form-item>
        </el-form>
        <div class="header-name">
          <el-button
            class="newBtn"
            style="margin-bottom: 5px;"
            size="mini"
            :disabled="isDisabled"
            @click="newHang"
          >{{ $t('btn.newHang') }}<!--新增行--></el-button>
          <search
            :options="selectData"
            :msg="tacitly"
            @seek="collect"
            @hand="processear"
          />
          <el-button
            type="primary"
            class="btn"
            size="mini"
            @click="processear"
          >
            {{ $t('btn.search') }}
          </el-button>
        </div>
        <jc-table
          :table-data="tableData"
          :table-header="tableHeard"
          :table-height="tableHeight"
          serial
          :get-summaries="getSummaries"
          show-summary
          @rowClick="techClick"
        >
          <!--组别-->
          <template v-slot:tagSlot="col">
            <el-select
              v-model="col.scope.row.fgroupId"
              :disabled="isDisabled"
              size="mini"
              @change="groupHandel(col.scope.$index)"
            >
              <el-option
                v-for="item in groupDetail"
                :key="item.groupId"
                :label="item.groupName"
                :value="item.groupId"
              />
            </el-select>
          </template>
          <!--工序编码-->
          <template v-slot:btnStates="col">
            <el-input
              v-model="col.scope.row.fprocessnumber"
              readonly="readonly"
              :disabled="isDisabled"
              size="mini"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="groupCli(col.scope.$index)"
              />
            </el-input>
          </template>
          <!--数量-->
          <template v-slot:billSlot="col">
            <el-input-number
              v-model.number="col.scope.row.fnum"
              :disabled="isDisabled"
              size="mini"
              @change="quantity(col.scope.$index)"
            />
          </template>
          <!--单价-->
          <template v-slot:orderSlot="col">
            <el-input-number
              v-model.number="col.scope.row.fprice"
              :disabled="isDisabled"
              size="mini"
              @change="quantity(col.scope.$index)"
            />
          </template>
          <!--备注-->
          <template v-slot:btnState="col">
            <el-input
              v-model="col.scope.row.fremark"
              :disabled="isDisabled"
              size="mini"
            />
          </template>
          <!--操作-->
          <template v-slot:btnSlot="col">
            <el-button
              type="danger"
              size="mini"
              :disabled="isDisabled"
              @click="proDelect(col.scope.$index)"
            >{{ $t('shop.delete') }}</el-button>
          </template>
        </jc-table>
        <jc-pagination
          v-show="total > 0"
          :total="total"
          :page.sync="pageNum"
          :limit.sync="pageSize"
          @pagination="queryWorkshopDetailsList"
        />
      </el-tab-pane>
      <el-tab-pane :label="$t('market.other')" name="journal">
        <jc-table
          :table-data="journalData"
          :table-header="journalHeard"
          :table-height="tableHeight1"
          serial
        />
        <jc-pagination
          v-show="journal.total > 0"
          :total="journal.total"
          :page.sync="journal.pageNum"
          :limit.sync="journal.pageSize"
          @pagination="journalLog"
        />
      </el-tab-pane>
    </el-tabs>
    <groupList v-if="groupVisable" :msg="groupId" @group="fprocesshandel" />
  </div>
</template>

<script>
import groupList from '@/views/workshop/technology/technologyDetail/components/groupDetailList'
import {
  queryWorkshopGroup,
  updateWorkshopCraftInfo,
  notSubmitWorkshopCraft,
  queryWorkshopCraftInfo,
  queryWorkshopDetailsList,
  reviewWorkshopCraft,
  notReviewWorkshopCraft,
  queryWorkshopCraftLog,
  checkAffectedBom, submitWorkshopCraft, deleteWorkshopCraftInfo
} from '@/api/processLibrary'
import { maxDecimal2 } from '@/utils/number'
import { toMxBmina } from '@/components/ToMxamineState'
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import jcButton from '@/components/Button'
import jumpMateriel from '@/components/JumpMateriel'

export default {
  components: {
    jcButton,
    groupList,
    search
  },
  mixins: [searData, jumpMateriel],
  data() {
    return {
      ftype: 14,
      fbillNo: 'fprocessname', // 工序名称
      groupVisable: false, // 工序编码列表弹窗
      activeName: 'first',
      active: 'first',
      process: {},
      isDisabled: false,
      groupId: '',
      groupDetail: [], // 组别
      seleceVisiblit: false, // 仓库
      indexSelf: 0,
      indexSelf1: 0,
      tableHeight: '46vh',
      tableHeight1: '500px',
      tableData: [],
      delArr: [],
      total: 0, // 总条目
      pageNum: 1, // 当前页
      pageSize: 200, // 每页显示多少条数据
      tableHeard: [
        { label: this.$t('market.tranches'), type: 'tag', prop: 'fgroupId', minWidth: '120px' },
        { label: this.$t('market.processname'), type: 'states', prop: 'fprocessnumber', minWidth: '120px' },
        { label: this.$t('market.processnumber'), prop: 'fprocessname', minWidth: '120px' },
        { label: this.$t('market.multiple'), type: 'bill', prop: 'fnum', minWidth: '120px' },
        { label: this.$t('market.fprice'), type: 'order', prop: 'fprice', minWidth: '120px' },
        { label: this.$t('market.billamount'), prop: 'fsumprice', minWidth: '120px' },
        { label: this.$t('market.note'), type: 'state', prop: 'fremark', minWidth: '120px' },
        { label: this.$t('market.handle'), type: 'btn' }
      ],
      journal: {
        total: 0, // 总条目
        pageNum: 1, // 当前页
        pageSize: 20 // 每页显示多少条数据
      },
      journalData: [],
      journalHeard: [
        { label: this.$t('market.operator'), prop: 'fname' },
        { label: this.$t('market.deaprt'), prop: 'fdeaprt' },
        { label: this.$t('market.describe'), prop: 'fdescribe' },
        { label: this.$t('market.ipSite'), prop: 'fip' },
        { label: this.$t('market.date1'), prop: 'createDate' }
      ],
      copys: 1,
      nary: [],
      processRules: {
        fdeptId: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ], fname: [
          { required: true, message: '请输入工艺名称', trigger: 'blur' }
        ], fcreateTime: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ], fmodel: [
          { required: true, message: '请输入型号', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    if (this.$route.params.id) {
      this.queryWorkshopDetail() // 表头
      // 注释原因 有时表格会渲染不出来
      // this.queryWorkshopDetailsList() // 表ge
    }
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 310px)' : '64vh'
    this.tableHeight1 = window.innerWidth > 1440 ? 'calc(100vh - 260px)' : '70vh'
  },
  methods: {
    // 点击获取日志
    handleClick(tab) {
      if (tab.name === 'journal') {
        this.journalLog()
      }
    },
    // 获取日志
    journalLog() {
      const DATA = {
        ...this.journal,
        fcraftId: this.process.fid
      }
      queryWorkshopCraftLog(DATA).then(res => {
        if (res.code === 0) {
          this.journalData = res.data.list
          this.journal.total = res.data.total
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 表头詳情
    queryWorkshopDetail(ev) {
      const DATA = {
        fid: this.process.fid || this.$route.params.id
      }
      queryWorkshopCraftInfo(DATA).then(res => {
        if (res.code === 0) {
          this.queryWorkshopDetailsList() // 表ge
          this.process = toMxBmina(res.data)
          this.isDisabled = this.process.fdocumentstatus === this.$t('market.state1') || this.process.fdocumentstatus === this.$t('market.state2')
          this.selectGroup()
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 表格
    queryWorkshopDetailsList() {
      const DATA = {
        fcraftId: this.process.fid || this.$route.params.id,
        search: this.searCollData
      }
      queryWorkshopDetailsList(DATA).then(res => {
        if (res.code === 0) {
          this.tableData = res.data.list
          this.tableData.map((item, index) => {
            item.fseq = index
          })
          // this.total = res.data.total
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 搜索
    processear() {
      this.pageNum = 1
      this.queryWorkshopDetailsList()
    },
    // 组别改变触发
    groupHandel(index) {
      const item = this.tableData[index]
      item.fprocessnumber = ''
      item.fprocessname = ''
      item.fprice = 0
      item.fremark = ''
      item.fgroupdetailId = '' // 工序明细ID
      item.fnum = 1
      item.fsumprice = 0
    },
    // 打开工序编码弹窗
    groupCli(index) {
      this.groupVisable = true
      this.indexSelf = index
      this.groupId = this.tableData[index].fgroupId
    },
    // 选择工序编码
    fprocesshandel(res) {
      const item = this.tableData[this.indexSelf]
      if (res.fprocessnumber) {
        item.fprocessnumber = res.fprocessnumber
        item.fprocessname = res.fprocessname
        item.fprice = res.fprice
        item.fgroupdetailId = res.fid // 工序明细ID
        item.fnum = 1
        item.fsumprice = maxDecimal2(item.fprice * item.fnum)
      }
      this.groupVisable = false
    },
    // 监听倍数 获取金额
    quantity(index) {
      const item = this.tableData[index]
      item.fsumprice = maxDecimal2(item.fprice * item.fnum)
    },
    // 根据生产部门查询对应组别
    selectGroup() {
      const DATA = {
        pageSize: 100,
        pageNum: 1,
        fdeptId: this.process.fdeptId
      }
      this.tableData = []
      queryWorkshopGroup(DATA).then(res => {
        if (res.code === 0) {
          this.groupDetail = res.data.list
          this.tableData.map(res => {
            res.groupId = ''
          })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 保存
    preserve(ev) {
      this.nary = []
      const { fdeptId, fname, fmodel, fid } = this.process
      const DATA = {
        fdeptId,
        fcraftId: fid,
        fname,
        fmodel,
        fdocumentStatus: 'A',
        delArr: this.delArr,
        list: this.tableData
      }
      for (const item of this.tableData) {
        if (!item.fprocessnumber || !item.fgroupId) {
          this.$message.warning('组别或工序编码不能为空！')
          return
        }
        this.nary.push(item.fprocessnumber)
      }
      const nary = this.nary.sort()
      for (const index in this.nary) {
        const index1 = Number(index) + 1 * 1
        if (nary[index] === nary[index1]) {
          this.$message.warning('重复的工序：' + nary[index])
          return false
        }
      }
      this.$refs.process.validate((valid) => {
        if (valid) {
          // 查询影响范围
          this.uploadScope(ev)
          this.CraftInfo = DATA
        } else {
          return false
        }
      })
    },
    // 修改
    shopCraftInfo(ev) {
      const DATA = {
        ...this.CraftInfo
      }
      updateWorkshopCraftInfo(DATA).then(res => {
        if (res.code === 0) {
          this.delArr = []
          if (ev === 1) {
            this.proSubmit(1)
          } else {
            this.queryWorkshopDetail() // 表头
            this.queryWorkshopDetailsList()
          }
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: [this.process.fid + ''] }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.queryWorkshopDetail() // 表头
        this.queryWorkshopDetailsList()
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 反提交
    proSubmit(ev) {
      const api = ev === 1 ? submitWorkshopCraft : notSubmitWorkshopCraft
      this.toExamineFun(api)
    },
    // 审核
    audit(ev) {
      const api = ev === 1 ? reviewWorkshopCraft : notReviewWorkshopCraft
      this.toExamineFun(api)
    },
    // 删除工艺
    delTechno() {
      this.$confirm('确认要删除么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        const DATA = { Numbers: [this.process.fid + ''] }
        deleteWorkshopCraftInfo(DATA).then(res => {
          if (res.code !== 0) {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
            return
          }
          // 关闭当前页面
          this.$store.dispatch('tagsView/guanbi', this.$route)
          this.$router.push({ path: '/technologyList' })
        })
      })
    },
    // 查询修改工艺模板影响范围
    uploadScope(ev) {
      const DATA = {
        fcraftId: this.process.fid
      }
      checkAffectedBom(DATA).then(res => {
        if (res.code === 0) {
          if (res.data.isNeedRemind === 1) {
            this.itemHTML = ''
            for (const item of res.data.list) {
              this.itemHTML += '<div>' + item + '</div>'
            }
            this.$msgbox({
              title: '提示',
              message: '此操作将影响以下物料,是否继续？' + this.itemHTML,
              dangerouslyUseHTMLString: true,
              showCancelButton: true,
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.shopCraftInfo(ev)
            })
          } else {
            this.shopCraftInfo(ev)
          }
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 点击表格行
    techClick(row) {
      this.indexSelf1 = row.fseq
    },
    // 新增行
    newHang() {
      const data = {
        fgroupId: '',
        fprocessnumber: '',
        fprocessname: '',
        fprice: '',
        fnum: 1,
        fsumprice: '',
        fremark: ''
      }
      this.tableData.push(data)
      this.tableData.map((item, index) => {
        item.fseq = index
      })
    },
    // 刪除
    proDelect(index) {
      const item = this.tableData[index]
      if (item.fid) {
        this.delArr.push(item.fid)
        this.tableData.splice(index, 1)
      } else {
        this.tableData.splice(index, 1)
      }
    }
  }
}
</script>
<style lang="scss" scope>
.editMaterial {
  @include listBom;
  .el-tabs {
    .header-name {
      position: relative;
      margin-top: 5px;
      margin-bottom: 12px;
      .search {
        margin-left: 100px;
      }
      .newBtn {
        transform: translateY(4px);
      }
      .btn {
        margin-left: 485px;
        transform: translateY(5px);
      }
    }
    .el-form {
      display: flex;
      flex-wrap: wrap;
      .el-input .el-input__inner {
        height: 30px;
        line-height: 30px;
      }
      .el-form-item {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        height: 35px;
        width: 275px;
        margin-bottom: 0;
        .btnType {
          margin-right: 5px;
        }

        .el-date-editor.el-input {
          width: 100% !important;
        }

        .el-select {
          width: 100%;
        }
      }
    }
  }
}
</style>
